// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: MIT

package logger

import (
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
	"time"
)

func TestFileRotator(t *testing.T) {
	basePath := "test.log"
	maxSize := int64(100) // 100 bytes
	maxAge := time.Second * 10

	// 清理残留文件
	cleanupLogs := func() {
		matches, _ := filepath.Glob(basePath + "*")
		for _, m := range matches {
			_ = os.Remove(m)
		}
	}
	cleanupLogs()
	t.Cleanup(cleanupLogs)

	fr := NewFileRotator(basePath, maxSize, maxAge)

	data := []byte("Test data that should cause a rotate")
	for i := 0; i < 10; i++ {
		n, err := fr.Write(data)
		if err != nil {
			t.Errorf("Write failed: %v", err)
		}
		if n != len(data) {
			t.Errorf("Write wrote %d bytes; want %d", n, len(data))
		}
	}

	newFiles, err := os.ReadDir(".")
	if err != nil {
		t.Fatalf("Failed to read directory: %v", err)
	}

	var createdLogs []string
	for _, file := range newFiles {
		if file.IsDir() {
			continue
		}
		if file.Name() == basePath || strings.HasPrefix(file.Name(), basePath+".") {
			createdLogs = append(createdLogs, file.Name())
		}
	}

	if len(createdLogs) == 0 {
		t.Fatalf("expected rotated log files to be created")
	}

	// 校验文件命名均为顺序数字后缀且数量受限
	maxSuffix := 0
	for _, name := range createdLogs {
		if name == basePath {
			continue
		}
		suffix := strings.TrimPrefix(name, basePath+".")
		idx, err := strconv.Atoi(suffix)
		if err != nil {
			t.Fatalf("expected numeric suffix, got %q", name)
		}
		if idx > maxSuffix {
			maxSuffix = idx
		}
	}
	if maxSuffix == 0 {
		t.Fatalf("expected at least one rotated file with numeric suffix, got %v", createdLogs)
	}
	if maxSuffix > defaultMaxFiles-1 {
		t.Fatalf("expected at most %d rotated files, got suffix %d", defaultMaxFiles-1, maxSuffix)
	}
}
